package com.cloudeasy.user.listener;

import com.cloudeasy.api.constant.AmqpConstant;
import com.cloudeasy.api.enums.ResultCodeEnum;
import com.cloudeasy.api.exception.CloudEasyException;
import com.cloudeasy.api.util.JsonUtil;
import com.cloudeasy.api.vo.amqp.ChangeOperateAreaVO;
import com.cloudeasy.user.service.UserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class UserListener {
    private final UserRoleService userRoleService;

    public UserListener(UserRoleService userRoleService) {
        this.userRoleService = userRoleService;
    }

    @RabbitListener(queuesToDeclare = @Queue(AmqpConstant.UserConstant.USER_CHANGE_AREA_ROUTING_KEY))
    public void process(String message) {
        ChangeOperateAreaVO changeOperateAreaVO = JsonUtil.fromJson(message, ChangeOperateAreaVO.class);
        if (changeOperateAreaVO == null) {
            throw new CloudEasyException(ResultCodeEnum.PARAMETER_ERROR);
        }
        log.info("{} 区域被删除", changeOperateAreaVO.getRawAreaName());
        log.info("角色管理提升至 {} 区域", changeOperateAreaVO.getTargetAreaName());
        userRoleService.changeOperateArea(changeOperateAreaVO.getRawAreaName(), changeOperateAreaVO.getTargetAreaName());
    }
}
